# -*- coding: utf-8 -*-
import hashlib, base64, random, string
from application import db
from sqlalchemy import and_, or_
from common.models.admin.erp_role_menu import ErpRoleMenu


class UserService():

    @staticmethod
    def geneAuthCode(user_info=None):
        m = hashlib.md5()
        str = "%s-%s-%s-%s" % (user_info.uid, user_info.login_name, user_info.login_pwd, user_info.login_salt)
        m.update(str.encode("utf-8"))
        return m.hexdigest()

    @staticmethod
    def genePwd(pwd, salt):
        m = hashlib.md5()
        str = "%s-%s" % (base64.encodebytes(pwd.encode("utf-8")), salt)
        m.update(str.encode("utf-8"))
        return m.hexdigest()

    @staticmethod
    def geneSalt(length=16):
        keylist = [random.choice((string.ascii_letters + string.digits)) for i in range(length)]
        return ("".join(keylist))

    @staticmethod
    def checkRoleMenu(rid, uid):
        exists = db.session.query(ErpRoleMenu).filter(
            and_(ErpRoleMenu.rid == rid, or_(ErpRoleMenu.uid == uid, ErpRoleMenu.uid == '0'))).count()
        if exists==1:
            return True
        else:
            return False
